package com.he.heblog.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.he.heblog.dto.ArticleDto;
import com.he.heblog.dto.UserDto;
import com.he.heblog.entity.*;
import com.he.heblog.service.*;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import net.sf.jsqlparser.statement.create.table.CreateTable;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.parameters.P;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Controller
@RequestMapping("/article")
public class ArticleController {
    @Autowired
    ArticleService articleService;
    @Autowired
    ArticletypeService articletypeService;
    @Autowired
    UserService userService;
    @Autowired
    TagService tagService;
    @Autowired
    CommentService commentService;
    @Autowired
    SupportService supportService;

    //新增文章
    @ResponseBody
    @PostMapping("/addArticle")
    public String addArticle(Article article) {
        System.out.println(article);
//    获取登录用户id
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        System.out.println("身份信息");
        System.out.println(authentication);
//    转成用户类型
        UserDto principal = (UserDto) authentication.getPrincipal();
//    设置文章所属用户ID
        article.setUserid(principal.getId());
//    设置文章发布时间
        article.setPublicTime(LocalDateTime.now());
//保存文章到数据库中
        articleService.save(article);
        return "成功创建";
    }
//跳转到文章编写页
    @GetMapping("/toWrite")
    public String toWrite(Model model) {
//    查询文章分类信息
        List<Articletype> list = articletypeService.list();
//    添加到模型中传递给视图
        model.addAttribute("typeList", list);
        return "/front/user/write";
    }

    @ResponseBody
    @GetMapping("/page")
    public Page<ArticleDto> getArticleList(Integer page, Integer pageSize) {
        Page<ArticleDto> articleListExtra = articleService.getArticleListExtra(page, pageSize, null);
        return articleListExtra;
    }
//根据文章id查询文章详情
//查询文章信息，查询文章对应的用户信息，查询文章对应的评论信息
    @GetMapping("/detail/{id}")
    public String getArticleDetail(@PathVariable Integer id, Model model) {
        ArticleDto articleDetail = articleService.getArticleDetail(id);
//        使文章浏览量加一
        Article byId = articleService.getById(id);
        Article article = new Article();
        article.setId(id);
        article.setVisitorVolume(byId.getVisitorVolume()+1);
        articleService.updateById(article);
//    查询文章对应的评论信息
        model.addAttribute("article", articleDetail);
        return "front/user/detail";
    }

    @ResponseBody
    @GetMapping("/detail/{id}/res")
    public ArticleDto getArticleDetail1(@PathVariable Integer id, Model model) {
        ArticleDto articleDetail = articleService.getArticleDetail(id);

        return articleDetail;
    }

    //根据文章的标签查询文章集合
    @GetMapping("/tag/{tagId}")
    public String getArticleBy(Model model, @PathVariable Integer tagId) {
        ArticleDto articleDto = new ArticleDto();
        articleDto.setTagId(tagId);
        Page<ArticleDto> articleCondition = articleService.getArticleCondition(1, articleDto);
        String url = "tag/" + tagId.toString();
        model.addAttribute("condition", url);
        model.addAttribute("ArticleList", articleCondition);
        return "front/user/condition";
    }

    @GetMapping("/tag/{tagId}/{page}")
    public String getArticleByPage(Model model, @PathVariable Integer page, @PathVariable Integer tagId) {
        ArticleDto articleDto = new ArticleDto();
        articleDto.setTagId(tagId);
        Page<ArticleDto> articleCondition = articleService.getArticleCondition(page, articleDto);
        String url = "tag/" + tagId.toString();
        model.addAttribute("condition", url);
        model.addAttribute("ArticleList", articleCondition);
        return "front/user/condition";
    }

    //    根据标题模糊搜索
    @GetMapping("/selectSubmit")
    public String getArticleByTitle(Model model, String selectMessage) {
        ArticleDto articleDto = new ArticleDto();
        articleDto.setTitle(selectMessage);
        Page<ArticleDto> articleCondition = articleService.getArticleCondition(1, articleDto);
        String url = "selectSubmit/" + selectMessage;
        model.addAttribute("condition", url);
        model.addAttribute("ArticleList", articleCondition);
        return "front/user/condition";

    }

    @GetMapping("/selectSubmit/{selectMessage}/{page}")
    public String getArticleByTitle(Model model, @PathVariable String selectMessage, @PathVariable Integer page) {
        ArticleDto articleDto = new ArticleDto();
        articleDto.setTitle(selectMessage);
        Page<ArticleDto> articleCondition = articleService.getArticleCondition(page, articleDto);
//        String url="selectSubmit/"+"?selectMessage="+selectMessage;
        String url = "selectSubmit/" + selectMessage;
        model.addAttribute("condition", url);
        model.addAttribute("ArticleList", articleCondition);
        return "front/user/condition";

    }

//    点赞文章或评论
//    后端应该保存用户对某个文章是否进行了点赞
//    点赞应该通知用户
    @ResponseBody
    @GetMapping("/support/{condition}/{Id}")
    public String supportArticleOrComment(@PathVariable String condition,@PathVariable Integer Id)
    {
     //获取当前用户
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
//        用户ID
        UserDto principal = (UserDto) authentication.getPrincipal();
        Integer id = principal.getId();
//        根据用户ID，文章ID查询点赞表，有则删除，无则添加
        LambdaQueryWrapper<Support> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Support::getUserId,id);
//        根据条件判断是堆什么进行了点赞
        if("article".equals(condition))
        wrapper.eq(Support::getArticleId,Id);
        if("comment".equals(condition))
         wrapper.eq(Support::getCommentId,id);
        Support one = supportService.getOne(wrapper);
        if(one==null){
            Support support = new Support();
            support.setArticleId(Id);
            support.setUserId(id);
            supportService.save(support);
//            增加文章对象中的点赞量属性
            Article origin = articleService.getById(Id);
            origin.setSupportCount(origin.getSupportCount()+1);
//            保存到文章对象中
            articleService.updateById(origin);
            return "点赞成功";
        }
        else{
           supportService.remove(wrapper) ;
            //            增加文章对象中的点赞量属性
            Article origin = articleService.getById(Id);
            origin.setSupportCount(origin.getSupportCount()-1);
//            保存到文章对象中
            articleService.updateById(origin);
           return "取消点赞成功";
        }

}



}
